package com.itzhoun.aspect;

import com.itzhoun.annotation.Ds;
import com.itzhoun.exception.handler.DynamicDataSourceContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author 周楠
 * @Date 2022/06/28/下午 4:33
 */
@Slf4j
@Aspect
@Component
//order注解表示组件加载顺序，值越小拥有越高的优先级
@Order(1)
public class DataSourceAspect {


    @Pointcut("@annotation(com.itzhoun.annotation.Ds)")
    public void dataSourcePointCut(){

    }

    @Around("dataSourcePointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable{
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Ds annotation = method.getAnnotation(Ds.class);
        if (annotation != null) {
            DynamicDataSourceContextHolder.setDataSourceType(annotation.value().name());
        }

        try {
            return joinPoint.proceed();
        }finally {
            //销毁数据源 在方法后执行
            DynamicDataSourceContextHolder.clearDataSourceType();
        }
    }




}
